import 'package:dio/dio.dart';
import 'package:myapp/api/Urls.dart';
import 'dart:async';

import 'package:myapp/util/Constant.dart';
import 'package:myapp/util/Utils.dart';

/*
 * 封装 restful 请求
 *
 * GET、POST、DELETE、PATCH
 * 主要作用为统一处理相关事务：
 *  - 统一处理请求前缀；
 *  - 统一打印请求信息；
 *  - 统一打印响应信息；
 *  - 统一打印报错信息；
 */
class DioUtils {
  /// global dio object
  static Dio dio;

  /// default options
  static const String API_PREFIX = 'https://novel.dkvirus.com/api/v1';
  static const int CONNECT_TIMEOUT = 10000;
  static const int RECEIVE_TIMEOUT = 3000;

  /// http request methods
  static const String GET = 'get';
  static const String POST = 'post';
  static const String PUT = 'put';
  static const String PATCH = 'patch';
  static const String DELETE = 'delete';

  ///Get请求测试
  static void getHttp<T>(
    String url, {
    parameters,
    Function(T t) onSuccess,
    Function(String error) onError,
  }) async {
    ///定义请求参数
    parameters = parameters ?? Map<String, dynamic>();
    try {
      Response response;
      Dio dio = createInstance();
      Options options;
      response =
          await dio.get(url, queryParameters: parameters, options: options);
      if (response.statusCode == 200) {
        if (onSuccess != null) {
          onSuccess(response.data);
        }
      } else {
        throw Exception('statusCode:${response.statusCode}');
      }
      print('响应数据：' + response.toString());
    } catch (e) {
      print('请求出错：' + e.toString());
      onError(e.toString());
    }
  }

  ///Post请求测试
  static void postHttp<T>(
    String url, {
    parameters,
    Function(T t) onSuccess,
    Function(String error) onError,
  }) async {
    ///定义请求参数
    var allParameters = Map<String, dynamic>();
    allParameters["type"] = url;
    allParameters["client_id"] = Constant.client_id;
    allParameters["timestamp"] = DateTime.now().millisecondsSinceEpoch;
    allParameters.addAll(parameters);
    var sign = getSign(allParameters);
    allParameters["sign"] = sign;
    try {
      Response response;
      Dio dio = createInstance();
      Options options = Options();
//      Map<String,dynamic> headerMap = Map();
//      headerMap["Access-Control-Allow-Origin"] = "*";
      options.headers = getHeaders();
      response = await dio.post(Urls.BaseUrl,
          queryParameters: allParameters, options: options);
      if (response.statusCode == 200) {
        if (onSuccess != null) {
          onSuccess(response.data);
        }
      } else {
        throw Exception('statusCode:${response.statusCode}');
      }
      print('响应数据：' + response.toString());
    } catch (e) {
      print('请求出错：' + e.toString());
      onError(e.toString());
    }
  }

  /// request method
  //url 请求链接
  //parameters 请求参数
  //metthod 请求方式
  //onSuccess 成功回调
  //onError 失败回调
  static Future<Map> request<T>(String url,
      {parameters,
      method,
      Function(T t) onSuccess,
      Function(String error) onError}) async {
    parameters = parameters ?? {};
    method = method ?? 'GET';

    /// 打印:请求地址-请求方式-请求参数
    print('请求地址：【' + method + '  ' + url + '】');
    print('请求参数：' + parameters.toString());

    Dio dio = createInstance();
    //请求结果
    var result;
    try {
      Response response = await dio.request(url,
          data: parameters, options: new Options(method: method));
      result = response.data;
      if (response.statusCode == 200) {
        if (onSuccess != null) {
          onSuccess(result);
        }
      } else {
        throw Exception('statusCode:${response.statusCode}');
      }
      print('响应数据：' + response.toString());
    } on DioError catch (e) {
      print('请求出错：' + e.toString());
      onError(e.toString());
    }

    return result;
  }

  /// 创建 dio 实例对象
  static Dio createInstance() {
    if (dio == null) {
      /// 全局属性：请求前缀、连接超时时间、响应超时时间
      var options = BaseOptions(
        connectTimeout: 15000,
        receiveTimeout: 15000,
        responseType: ResponseType.plain,
        validateStatus: (status) {
          // 不使用http状态码判断状态，使用AdapterInterceptor来处理（适用于标准REST风格）
          return true;
        },
        baseUrl: "http://poetry.huhustory.com/",
      );

      dio = new Dio(options);
    }

    return dio;
  }

  /// 清空 dio 对象
  static clear() {
    dio = null;
  }

  static String getSign(Map<String, dynamic> allParameters) {
    Map<String, dynamic> map = sorMap(allParameters);
    String stringBuffer = "";
    stringBuffer = stringBuffer + Constant.client_secret;
    for (String key in map.keys) {
      stringBuffer = stringBuffer + key;
      stringBuffer = stringBuffer + map[key].toString();
    }
    stringBuffer = stringBuffer + Constant.client_secret;
    return Utils.generateMd5(stringBuffer).toUpperCase();
  }

  static sorMap(Map<String, dynamic> allParameters) {
    List<String> keys = allParameters.keys.toList();
    // key排序
    keys.sort((a, b) {
      List<int> al = a.codeUnits;
      List<int> bl = b.codeUnits;
      for (int i = 0; i < al.length; i++) {
        if (bl.length <= i) return 1;
        if (al[i] > bl[i]) {
          return 1;
        } else if (al[i] < bl[i]) return -1;
      }
      return 0;
    });
    var map = Map<String, dynamic>();
    for (String key in keys) {
      map[key] = allParameters[key];
    }
    return map;
  }

  static Map<String,dynamic> getHeaders () {
    return {
      'Accept': 'application/json, text/plain, */*',
      'Content-Type': 'application/json',
      'Authorization': "**",
      'User-Aagent': "4.1.0;android;6.0.1;default;A001",
      "HZUID": "2",
    };
  }
}
